var express = require('express');
var router = express.Router();
var moment = require('moment');
//import common modules
var myTool = require("../../app_modules/common/myTool.js");
var gridfs = require("../../app_modules/common/gridfsTool.js");
var user =  require('../../app_modules/dbAccess/user_Mongo.js');



/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('user/index', { title: 'user' });
});



/***************common function begin****************/
function verifySign(req, res,next){	
	myTool.verifyToken(req,res,user,next);
}
/***************common function end****************/







/***************Add user begin****************/
router.post('/add',verifyAddUser,function (req, res) {
	var pwd=req.body.password;
	pwd=myTool.encrypt(pwd,'md5');	
    var token="signout";
	var userObj = {
	    code:req.body.code.toLowerCase().replace(/\s+/g,''),
	    name: req.body.name,
	    mail: req.body.mail.toLowerCase().replace(/\s+/g,''),
	    telephone: req.body.telephone.toLowerCase().replace(/\s+/g,''),
	    phone: myTool.getResult(req.body.phone,""),
	    address: myTool.getResult(req.body.address,""),
	    remark: myTool.getResult(req.body.remark,""),
	    companyCode: myTool.getResult(req.body.companycode,""),
	    companyName: myTool.getResult(req.body.companyname,""),
	    status:"active",
	    password:pwd,
	    createDate:new Date(),
	    token:token,
		metadata:req.body.metadata    
	};
	new user().add(userObj, function (err, rs) {
	    if (err)return res.json({ result: false,messageflag:"faild",message:"save faild." });
	    else return res.json({ result: true,messageflag:"success",message:"save successfully." });
	});
});

function verifyAddUser(req, res, next){
	//check the required input  
    var mailRegExp = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    var phoneRegExp=/^1[34578]\d{9}$/;
    var codeRegExp=/^[a-zA-Z\d]+$/;

    if(myTool.getResult(req.body.password,"")=="")
    	return  res.json({ result: false,messageflag:"psd_required",message:"password is required." });
    else if(myTool.getResult(req.body.code,"")=="")
    	return res.json({ result: false,messageflag:"code_required",message:"code is required." });
    else if(!codeRegExp.test(req.body.code))
    	return res.json({ result: false,messageflag:"code_formatError",message:"code format error." });
    else if(myTool.getResult(req.body.name,"")=="")
    	return  res.json({ result: false,messageflag:"name_required",message:"name is required." });    	
    else if(myTool.getResult(req.body.mail,"")=="")
    	return  res.json({ result: false,messageflag:"mail_required",message:"mail is required." });  
    else if(!mailRegExp.test(req.body.mail))
    	return res.json({ result: false,messageflag:"mail_formatError",message:"mail format error." });  
    else if(myTool.getResult(req.body.telephone,"")=="")
    	return  res.json({ result: false,messageflag:"telephone_required",message:"telephone is required." });
    else if(!phoneRegExp.test(req.body.telephone))
    	return res.json({ result: false,messageflag:"telephone_formatError",message:"telephone format error." });  
    else{
    	//check exist the code
	    var code=req.body.code.toLowerCase().replace(/\s+/g,'');
	    var tel=req.body.telephone.toLowerCase().replace(/\s+/g,'');
	    var mail=req.body.mail.toLowerCase().replace(/\s+/g,'');
	    user.find().or([ {code:code},{telephone:tel},{mail:mail} ])
	    .select('code telephone mail')
	    .limit(1)
	    .exec(function(err,result){
		   	 if (err)return res.json({ result: false,messageflag:"error",message:"application error." ,data:null});
		   	 else if (result!=null){
		   	 	    console.log(result[0]);
		        	if(result.length>0&&result[0].code==code)return res.json({ result: false,messageflag:"code_exist",message:"code has exist ." });
		        	else if(result.length>0&&result[0].mail==mail)return res.json({ result: false,messageflag:"mail_exist",message:"mail has exist." });
		        	else if(result.length>0&&result[0].telephone==tel)return res.json({ result: false,messageflag:"telphone_exist",message:"telephone has exist." });
		        	else next();
		        }
		 });
     }    
}

/***************Add user end****************/









/**************sign in start***************/
//sign in
router.post('/sign',function (req, res) {
    //check the required input      
    if(myTool.getResult(req.body.account,"")==""){
    	return res.json({ result: false,messageflag:"account_required",message:"account is required." ,data:null});
    }
    else if(myTool.getResult(req.body.password,"")==""){
    	 return res.json({ result: false,messageflag:"psd_required",message:"password is required." ,data:null});
    }
    else{
    	var pwd=req.body.password;
		pwd=myTool.encrypt(pwd,'md5');
	    var re=req.body.account.toLowerCase().replace(/\s+/g,'');

	    user.find().where("status","active")
	   .or([ {code:re},{telephone:re},{mail:re} ])
	   .select('code name password telephoe mail token')
	   .limit(1)
	   .exec(function(err,result){
	   	 if (err)return res.json({ result: false,messageflag:"error",message:"application error." ,data:null});
	   	 else if (result!=null){
	        	if(result.length>0&&result[0].password==pwd)GetSignToken(req,res,result[0]);
	        	else return res.json({ result: false,messageflag:"psd_incorrect",message:"The password incorrect." });
	        }
	   });
    }
});

function GetSignToken(req,res,result){
	var flag=myTool.tokenValid(result.token);
	if (flag) {
		return res.json({result: true,messageflag:"old_token",message:"sign successfully.",data:result});
	}
	else{
		var token=myTool.jwtCreateToken(result.code);
		changeToken(result.code,token);
	    result.token=token;
        return res.json({result: true,messageflag:"new_token",message:"sign successfully.",data:result});
	}
}

function changeToken(code,token){
    user.update({ code: code }, {
        $set: {
            token: token,
        }
    },function (err, rs) {
    });
}

//sign out
router.post('/signOut',function (req, res) {
   var oldToken=myTool.getResult(req.query.token,"");
   if(oldToken=="")return res.json({result: false,messageflag:"token_required",message:"the token is required."});
   else{
	   	user.update({ token: oldToken }, {
	        $set: {
	            token: "signout",
	        }
	    }, function (err, rs) {
	        if(err)return res.json({result: false,messageflag:"error",message:"application error."});
	        else return res.json({result: true,messageflag:"success",message:"sign out successfully."});        
	    });
   }
});
/**************sign in end***************/






/**************other user comment method start***************/

//获取用户信息
router.post('/getSignUser',verifySign,function (req, res) {
    var resultObj = user.findOne({ "token": req.query.token},'-_id -token -password -createDate -__v', function (err, result) {
        if (err) return res.json({ result: false,messageflag:"error",message:"application error." });                 
        else if (result!=null)return res.json({result: true,messageflag:"success",message:"successfully.",data:result});
        else return res.json({ result: false,messageflag:"token_incorrect",message:"The token incorrect." });
     });
});

//上传用户头像
var multiparty = require('multiparty');
router.post('/userIconUp',verifySign, function (req, res, next) {
	var token=req.query.token;
    var form = new multiparty.Form({ uploadDir: './public/files/upload/' });    
    form.parse(req, function (err, fields, files) {
        if(!err){
        	for(i=0;i<1;i++){
        		var inputFile = files.inputFile[i];
	        	var mongoose = require('mongoose');	        			
                var id = new mongoose.mongo.ObjectID();
	        	var metadata={name:"yeyu","createBy":"yeyu"};
                gridfs.uploadFIle(id,inputFile,metadata)   

                user.update({ token: token }, {
			        $set: {
			        	"icon":id
			        }
			     },function(err){});
            }
            res.send("success.");
           }
           else{res.send("faild"+err.message);}
           
       });

});
//获取用户头像
// router.post('/getIcon',verifySign, function (req, res, next) {
// 	var token=req.query.token;
// 	gridfs.getGridfs("",res);
// });

//调用存储过程
router.post('/invokeProcData',verifySign, function (req, res, next) {
	gridfs.invokeProcData("",res);
});


/**************other user comment method end***************/


module.exports = router;